package com.sparrow.common.util;


import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子自旋工具类
 */
public class AtomicUtil {

    // AtomicReference 自旋设置
    public static <T> void spinSet(AtomicReference<T> ref, T update) {
        T expect;
        do {
            expect = ref.get();
            Thread.yield(); // 可选，降低CPU占用
        } while (!ref.compareAndSet(expect, update));
    }

    // AtomicInteger 自旋设置
    public static void spinSet(AtomicInteger ref, int update) {
        int expect;
        do {
            expect = ref.get();
            Thread.yield();
        } while (!ref.compareAndSet(expect, update));
    }

    // AtomicLong 自旋设置
    public static void spinSet(AtomicLong ref, long update) {
        long expect;
        do {
            expect = ref.get();
            Thread.yield();
        } while (!ref.compareAndSet(expect, update));
    }

    // AtomicBoolean 自旋设置
    public static void spinSet(AtomicBoolean ref, boolean update) {
        boolean expect;
        do {
            expect = ref.get();
            Thread.yield();
        } while (!ref.compareAndSet(expect, update));
    }
}

